/**
 * Created by showtan on 2018/12/27.
 * 导航
 */

import '../constants/Global';
import Navigator from './StackNav';
import JPushModule from 'jpush-react-native'; // 极光
// import _ from 'lodash';

// Text.prototype.render = _.wrap(Text.prototype.render, function (func, ...args) {
//   let originText = func.apply(this, args);
//   return React.cloneElement(originText, {
//     allowFontScaling: false,
//     style: [
//       {
//         fontSize: adapt(14),
//         color: '#000',
//         fontFamily: 'PingFangSC-Regular'
//       },
//       originText.props.style,
//     ]
//   })
// });

// Text.defaultProps = Object.assign({}, Text.defaultProps, { fontFamily: 'Georgia' });

class Root extends Component {
  state = { time: 3 };
  componentDidMount() { // 1、接口请求广告页面，请求成功后再隐藏屏显（接口中图片需要适配iPhoneX(XS)、XR、XS MAX、其他）  2、热更新替换
    this.props.dispatch({ type: 'task/changeNum', payload: { num: 2 } });
    this.timer = setInterval(() => this.setState({ time: this.state.time - .5 }), 500);
    if (Platform.OS === 'android') {
      JPushModule.initPush();
      JPushModule.notifyJSDidLoad(resultCode => {
        if (resultCode === 0) {
        }
      });
    } else {
      JPushModule.setupPush();
    }
    JPushModule.getRegistrationID((registrationId) => { // 获取registrationId
      console.log('registrationId', registrationId)
    });
    JPushModule.addReceiveNotificationListener((message) => { // 接收推送通知
      console.log(message)
    });
    JPushModule.addReceiveOpenNotificationListener((message) => { // 打开通知
      if (isIOS) {
        // JPushModule.getBadge(badge => { // 得到应用小红点数
        // 	console.log(badge);
        // });
        JPushModule.setBadge(0, success => { // 点开通知设置应用小红点数为0
          console.log(success);
        });
      }
    });
    JPushModule.getRegistrationID((registrationId) => { // 获取registrationId
      YXStorage.save('cid', { cid: registrationId });
    });
    AppState.addEventListener('change', this.handleAppStateChange);
    // var callback = message => {
    //   console.log('alertContent: ' + JSON.stringify(message))
    // }
    // JPushModule.addReceiveCustomMsgListener(callback);  // 接收自定义消息
  }
  handleAppStateChange = (appState) => { // 状态改变响应
    // if (appState == 'background' || appState == 'inactive') {
    //   JPushModule.setBadge(0, success => { // 切换至后台运行/切换过程设置应用小红点数
    //     console.log(success);
    //   });
    // }
  }
  componentDidUpdate() {
    if (this.state.time == -.5) {
      this.timer && clearInterval(this.timer);
    }
  }
  componentWillUnmount() {
    AppState.removeEventListener('change', this.handleAppStateChange);
  }
  render() {
    return (
      <View style={{ flex: 1 }}>
        {
          this.state.time == -.5 ? <Navigator screenProps={this.props.task.num == 0 ? -1 : this.props.task.num} /> : //screenProps不能为0否则为{}
            <ImageBackground source={Images.other.icon_splash} style={{ width: width, height: height }}>
              <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginHorizontal: adapt(10), marginTop: isIphoneX() ? adapt(60) : isIOS ? adapt(35) : adapt(15) }}>
                <Text style={{ color: '#fff', fontSize: adapt(12) }}>广告</Text>
                <TouchableOpacity onPress={() => this.setState({ time: -.5 })} activeOpacity={1} style={{ backgroundColor: '#8a9499', width: adapt(60), height: adapt(28), borderRadius: adapt(15), justifyContent: 'center', alignItems: 'center' }}>
                  <Text style={{ fontSize: adapt(12), color: '#fff' }}>{Math.round(this.state.time) + ' 跳过'}</Text>
                </TouchableOpacity>
              </View>
            </ImageBackground>
        }
      </View>
    )
  }
}
Root.proptypes = {
  task: PropTypes.object,
  dispatch: PropTypes.func
}
function mapStateToProps({ task }) {
  return { task }
}
export default connect(mapStateToProps)(Root)

/**
 * Android 返回
 */
BackHandler.addEventListener('hardwareBackPress', () => {
  if (this._navigator && this._navigator.getCurrentRoutes().length > 1) {
    this._navigator.pop();
    return true;
  }
  if (this.lastBackPressed && this.lastBackPressed + 2000 > Date.now()) {
    return false
  }
  this.lastBackPressed = Date.now()
  ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT)
  return true;
})